<?php

namespace app\controller\sys;

use think\App;
use think\Response;
use think\Validate;
use think\facade\View;
use think\facade\Config;
use think\facade\Session;
use think\exception\HttpResponseException;
use think\exception\ValidateException;

use app\BaseController;
use app\utils\ReUtils;
use app\model\SysMenu as SysMenuModel;

class Base extends BaseController
{
    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = ['app\middleware\Admin'];
    
    /**
     * 用户信息
     */
    protected $sysUser;

    /**
     * 系统信息
     */
    protected $system;

    protected $modelName;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->init();
    }

    public function init()
    {
        $eng = View::engine();

        $eng->layout('sys/layout');

        // 左侧菜单
        $rid = Session::get('adminuser.roleid');

        $menus = $rid != null ? SysMenuModel::getUserMenuList($rid) : [];
        $controller =  str_replace("sys.", "", strtolower(preg_replace('/(?<=[a-z])([A-Z])/', '_$1', $this->request->controller())));

        $action = strtolower(preg_replace('/(?<=[a-z])([A-Z])/', '_$1', $this->request->action()));

        $route =  $controller . '/' . $action;
        $breadCrumb = SysMenuModel::getBreadCrumb($route);

        // layer open
        if ($this->request->has('_layer')) {
            View::assign('layer', true);
        } else {
            View::assign('layer', false);
        }

        $system       = \app\model\System::find(1);
        $this->system = $system;
        View::assign([
            'active_pid' => $breadCrumb['active_pid'],
            'breadCrumb' => $breadCrumb['breadCrumb'],
            'menus' => $menus,
            'system' => $system,
            'sys_version'    => Config::get('app.sys_version'),
            'default_lang' => env('lang.default_lang', 'en-us')
        ]);
    }

    // 获取当前登录用户信息
    protected function getSysUser()
    {
        if (!$this->sysUser) {
            $this->sysUser = \app\model\SysUser::where('userid', session('adminuser.userid'))->find();
        }
        return $this->sysUser;
    }

    /**
     * 验证数据
     * @access protected
     * @param array        $data     数据
     * @param string|array $validate 验证器名或者验证规则数组
     * @param array        $message  提示信息
     * @param bool         $batch    是否批量验证
     * @return array|string|true
     * @throws ValidateException
     */
    protected function validate(array $data, $validate, array $message = [], bool $batch = false)
    {
        if (is_array($validate)) {
            $v = new Validate();
            $v->rule($validate);
        } else {
            if (strpos($validate, '.')) {
                // 支持场景
                list($validate, $scene) = explode('.', $validate);
            }
            $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
            $v     = new $class();
            if (!empty($scene)) {
                $v->scene($scene);
            }
        }

        $v->message($message);

        //是否批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }

        $result = $v->failException(false)->check($data);
        if (true !== $result) {
            return $v->getError();
        } else {
            return $result;
        }
    }

    /**
     * 操作成功跳转的快捷方法
     * @access protected
     * @param  mixed $msg 提示信息
     * @param  string $url 跳转的URL地址
     * @param  mixed $data 返回的数据
     * @param  integer $wait 跳转等待时间
     * @param  array $header 发送的Header信息
     * @return void
     */
    protected function success($msg = '', string $url = null, $data = '', int $wait = 3, array $header = [])
    {
        if (is_null($url) && isset($_SERVER["HTTP_REFERER"])) {
            $url = $_SERVER["HTTP_REFERER"];
        } elseif ($url) {
            $url = (strpos($url, '://') || 0 === strpos($url, '/')) ? $url : (string)$this->app->route->buildUrl($url);
        }

        $result = [
            'code' => 0,
            'msg' => $msg,
            'data' => $data,
            'url' => $url,
            'wait' => $wait,
        ];

        $type = $this->request->isJson() || $this->request->isAjax() ? 'json' : 'html';
        // 把跳转模板的渲染下沉，这样在 response_send 行为里通过getData()获得的数据是一致性的格式
        if ('html' == strtolower($type)) {
            $type = 'view';
            $response = Response::create($this->app->config->get('jump.dispatch_success_tmpl'), $type)->assign($result)->header($header);
        } else {
            $response = Response::create($result, $type)->header($header);
        }

        throw new HttpResponseException($response);
    }

    /**
     * 操作错误跳转的快捷方法
     * @access protected
     * @param  mixed $msg 提示信息
     * @param  string $url 跳转的URL地址
     * @param  mixed $data 返回的数据
     * @param  integer $wait 跳转等待时间
     * @param  array $header 发送的Header信息
     * @return void
     */
    protected function error($msg = '', string $url = null, $data = '', int $wait = 3, array $header = [])
    {
        if (is_null($url)) {
            $url = $this->request->isAjax() ? '' : 'javascript:history.back(-1);';
        } elseif ($url) {
            $url = (strpos($url, '://') || 0 === strpos($url, '/')) ? $url : (string)$this->app->route->buildUrl($url);
        }

        $result = [
            'code' => 1,
            'msg' => $msg,
            'data' => $data,
            'url' => $url,
            'wait' => $wait,
        ];

        $type = $this->request->isJson() || $this->request->isAjax() ? 'json' : 'html';

        if ('html' == strtolower($type)) {
            $type = 'view';
            $response = Response::create($this->app->config->get('jump.dispatch_error_tmpl'), $type)->assign($result)->header($header);
        } else {
            $response = Response::create($result, $type)->header($header);
        }

        throw new HttpResponseException($response);
    }

    /**
     * 删除
     * @param int|array $id  info id
     * @return array
     */
    public function delete($id)
    {
        if ($this->request->isPost()) {
            $model = '\app\model\\' . $this->modelName;
            if ($model ::destroy($id)) {
                return ReUtils::success();
            } else {
                return ReUtils::error();
            }
        }
    }

    // 排序
    public function sort()
    {
        if ($this->request->isPost()) {
            $param  = $this->request->param();

            $model = '\app\model\\' . $this->modelName;

            return $model::sorts($param);
        }
    }

    // 状态变更
    public function status(int $id)
    {
        if ($this->request->isPost()) {
            $model = '\app\model\\' . $this->modelName;
            return $model::state($id);
        }
    }
}
